package com.xuecheng.search.infrastructure.util;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-09-01  10:30
 */
public class EsUtil {

    /**
     * 设置分页
     * @param searchSourceBuilder
     * @param curPage
     * @param pageSize
     * @return
     */
    public static SearchSourceBuilder setPages(SearchSourceBuilder searchSourceBuilder, Long curPage, Long pageSize){
        int from = (int)((curPage - 1) * pageSize);
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(Math.toIntExact(pageSize));
        return searchSourceBuilder;
    }

    /**
     * 获取聚合结果
     * @param aggregations
     * @param aggName
     * @return
     */
    public static List<String> getAggregation(Aggregations aggregations, String aggName){
        if (Objects.isNull(aggregations)){
            return new ArrayList<>();
        }
        // 根据聚合名称获取聚合结果
        Terms terms = aggregations.get(aggName);
        //组装结果
        return terms.getBuckets()
                .stream()
                .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                .collect(Collectors.toList());
    }


    /**
     * 高亮设置
     * @return
     */
    public static HighlightBuilder setHighlight(String params){
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font class='eslight'>");
        highlightBuilder.postTags("</font>");
        // 设置高亮字段
        highlightBuilder.fields().add(new HighlightBuilder.Field(params));
        return highlightBuilder;
    }
}
